const express = require('express')
const router = express.Router()
const News = require('../../model/News')
const Comment = require('../../model/Comment')

//添加新闻
router.post('/add', (req, res) => {
  const news_info = req.body
  new News(news_info).save().then(news => {
    res.json(news)
  })
});

//查询新闻
router.get('/', (req, res) => {
  const news = News.find()
    .then(news => news)
    .catch(err => res.status(404).json(err))
  const comments = Comment.find()
    .then(comments => comments)
    .catch(err => '没有内容')
  Promise.all([news, comments])
    .then(result => {
      const arr = []
      result[0].forEach(item => {
        const obj = {}
        obj._id = item._id
        obj.title = item.title
        obj.content = item.content
        obj.author = item.author
        obj.date = item.date
        obj.topic = item.topic
        const comments = result[1].filter(com => com.nid == item._id)
        obj.comments = comments.length
        arr.push(obj)
      })
      res.json(arr)
    })
    .catch(err => res.json('没有内容'))
})

// 删除新闻
router.delete('/delete/:id', (req, res) => {
  const news = News.findOneAndRemove({
    _id: req.params.id
  }).then(news => '删除成功')
    .catch(err => '删除失败')
  const comment = Comment.remove({
    nid: req.params.id
  }).then(comment => '删除成功')
    .catch(err => '删除失败')
  Promise.all([news, comment]).then(result => res.json('删除成功'))
})

//查询单个新闻
router.get('/search/:id', (req, res) => {
  News.findOne({
    _id: req.params.id
  })
    .then(news => {
      if (!news) {
        return res.status(404).json('没有任何内容')
      }
      res.json(news)
    })
    .catch(err => res.status(404).json(err))
})

//编辑新闻
router.post('/update/:id', (req, res) => {
  News.findOneAndUpdate({
    _id: req.params.id
  }, {
    $set: req.body
  }, {
    new: true
  }).then(news => res.json(news))
})

//关键词查询新闻
router.post('/search', (req, res) => {
  News.find(
    {title: {$regex: req.body.keyword, $options: 'i'}}
  )
    .then(news => {
      if (!news) {
        return res.status(404).json('没有任何内容')
      }
      res.json(news)
    })
    .catch(err => res.status(404).json(err))
})

//今日要闻
router.get('/todayNews', (req, res) => {
  let todayNews = new Set()
  News.find()
    .then(news => {
      if (!news) {
        return res.status(404).json('没有任何内容')
      }
      for (let i = 0; i < 5; i++) {
        todayNews.add(news[Math.floor(Math.random() * news.length)])
      }
      res.json([...todayNews])
    })
    .catch(err => res.status(404).json(err))
})

//侧边栏
router.get('/sidebar', (req, res) => {
  const sidebar = [{
    title: '今日话题',
    url: 'topic.png'
  }, {
    title: '国内新闻',
    url: 'homenews.jpg'
  }, {
    title: '国外新闻',
    url: 'guowai.jpg'
  }]
  News.find()
    .then(news => {
      sidebar.forEach(item => {
        let sidebarItem = news.filter((n) => {
          return n.topic === item.title
        })
        item.content = sidebarItem
      })
      res.json(sidebar)
    })
    .catch(err => res.status(404).json(err))
})

router.get('/img', (req, res) => {
  req.query.url ? res.download(`asset/img/${req.query.url}`) : res.send({
    success: false
  })
})


module.exports = router